<?php

// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2019 http://shopxo.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------

namespace app\service;

use think\Db;
use think\facade\Hook;

/**
 * 到货提醒服务层
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-01T21:51:08+0800
 */
class ArrivalreminderService {

    /**
     * 获取到货提醒列表
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-08-29
     * @desc    description
     * @param   array           $params [输入参数: where, field, is_photo]
     */
    public static function arrivalReminderList($params = [], $flat = 0) {


        $where = empty($params['where']) ? [] : $params['where'];

        $order_by = empty($params['order_by']) ? 'id desc' : trim($params['order_by']);

        $m = isset($params['m']) ? intval($params['m']) : 0;
        $n = isset($params['n']) ? intval($params['n']) : 10;
        $data = Db::name('ArrivalReminder')->where($where)->order($order_by)->limit($m, $n)->select();

        return DataReturn('处理成功', 0, $data);
    }

    /**
     * 后台管理到货提醒列表条件
     * @author   csb
     *  
     * @param    [array]          $params [输入参数]
     */
    public static function ArrivalreminderWhere($params = []) {
        $where = [
        ];
        if (isset($params['type_num']) && $params['type_num'] > 0) {
            switch ($params['type_num']) {
                case 1:
                    $where[] = ['status', '=', 0];
                    break;
                case 2:
                    $where[] = ['status', '=', 1];
                    break;
                case 3:  //未到货

                    break;
                case 4:
                    $where[] = ['status', '=', 2];
                    break;
            }
        }
        // 模糊 
        if (!empty($params['keywords'])) {
            $where[] = ['title', 'like', '%' . $params['keywords'] . '%'];
        }

        // 是否更多条件
        if (isset($params['is_more']) && $params['is_more'] == 1) {
            // 时间
            if (!empty($params['time_start'])) {
                $where[] = ['add_time', '>', strtotime($params['time_start'])];
            }
            if (!empty($params['time_end'])) {
                $where[] = ['add_time', '<', strtotime($params['time_end'])];
            }
            // 用户
            if (!empty($params['username'])) {
                $where[] = ['username', 'like', '%' . $params['username'] . '%'];
            }
        }
        return $where;
    }

    /**
     * 获取到货提醒总数
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-07
     * @desc    description
     * @param   [array]           $where [条件]
     */
    public static function ArrivalReminderTotal($where = []) {
        return (int) Db::name('ArrivalReminder')->where($where)->count();
    }

    public static function changeStatus($params = []) {
        // 请求参数
        $p = [
            [
                'checked_type' => 'empty',
                'key_name' => 'id',
                'error_msg' => '操作id有误',
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'field',
                'error_msg' => '未指定操作字段',
            ],
            [
                'checked_type' => 'in',
                'key_name' => 'state',
                'checked_data' => [0, 1],
                'error_msg' => '状态有误',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if ($ret !== true) {
            return DataReturn($ret, -1);
        }
        $ids = explode(",", $params['id']);

        $where[] = ['ar.id', 'in', $ids];
        $arrivalReminderInfo = Db::name('ArrivalReminder')->field("ar.id,g.title,u.weixin_openid,u.username,u.mobile,ar.status")->alias("ar")->join(['__USER__' => 'u'], "u.id=ar.user_id")->join(['__GOODS__' => 'g'], "g.id=ar.goods_id")->where($where)->select();
            
        $i = 0;  //统计提醒的个数
        if (count($arrivalReminderInfo) > 0) {
            foreach ($arrivalReminderInfo as $v) {
                if ($v['status'] != 0) {
                    continue;
                }
                $data = [
                    'touser' => $v['weixin_openid'], //接受者OPENID
                    'template_id' => "SRu_UWjgrbun3CacoCV1LrTRn0bK0cG9evsa8s25090",
                    'page' => "index", //跳转到小程序页面
                    'data' => [
                        "name1" => [
                            "value" => "典书"
                        ],
                        "thing2" => [
                            "value" => "您订阅的书籍已有现货，请您尽快前往购买"
                        ],
                        "time3" => [
                            "value" => date('Y-m-d H:i:s')
                        ]
                    ],
                
                ];
            
                $is_success = false;
                // 短信提醒   
                // 判断用户是否绑定了手机号码     
                if (isset($v['mobile']) || !empty($v['mobile'])) {
                    $verify_params = array(
                        'key_prefix' => 'reg',
                        'expire_time' => MyC('common_verify_expire_time'),
                        'time_interval' => MyC('common_verify_time_interval'),
                    );
                    $obj = new \base\Sms($verify_params);
                   // $obj->SendDaohuo($v['mobile'], $v['username'], $v['title'], MyC('common_sms_daohuo_template'));    
                    $is_success = true;
                }
                //消息模板发送    
                $result = (new \base\Wechat(MyC('common_app_mini_weixin_appid'), MyC('common_app_mini_weixin_appsecret')))->subscribeMessage($data);

                if ($result['msg'] == "ok" && $result['code'] == -1) {
                    $is_success = true;
                }
                if ($is_success) {
                    $is_update = Db::name('ArrivalReminder')->where(['id' => $v['id']])->update([$params['field'] => intval($params['state']),"upd_time"=>time()]);
                    if ($is_update){  $i++;}
                }
            }
        }
        if ($i == count($arrivalReminderInfo)) {
            return DataReturn('提醒成功');
        } else {
            return DataReturn("已提醒$i个");
        }
    }

}

?>